package com.gzw.dms.activity;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.UpdateManager;
import com.gzw.dms.adapter.MainViewPagerAdapter;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.bean.AppInfo;
import com.gzw.dms.bean.Constant;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    private Toolbar toolbar;
    private LinearLayout lianer_tab;
    private DrawerLayout drawer;
    private ActionBarDrawerToggle toggle;
    private NavigationView navigationView;
    private MainViewPagerAdapter mainAdapter;
    private ViewPager mViewPager;
    private List<Class> lsFragment = new ArrayList<>();
    private List<ImageView> lsImageView = new ArrayList<>();
    private List<TextView> lsTextView = new ArrayList<>();
    private List<View> lsTabView = new ArrayList<>();
    private String[] titles = {"待配运单", "配送运单", "签收查询"};
    private TextView tv_name, tv_accunt, tv_bbh;
    //    private int selectIndex=0;
    private Context mContext;
    int viewPagerH = 0;
    int viewPagerW = 0;
    private String NowVersion;
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initViews() {
        lianer_tab = (LinearLayout) findViewById(R.id.layout_tab);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);
        tv_name = (TextView) headerView.findViewById(R.id.nav_userName);
        tv_accunt = (TextView) headerView.findViewById(R.id.nav_accunt);
        tv_bbh = (TextView) headerView.findViewById(R.id.nav_bbh);
        mViewPager = (ViewPager) findViewById(R.id.container);

        lsTextView.add((TextView) findViewById(R.id.tv_home));
        lsTextView.add((TextView) findViewById(R.id.tv_order));
//        lsTextView.add((TextView) findViewById(R.id.tv_fj));
        lsTextView.add((TextView) findViewById(R.id.tv_my));

        lsImageView.add((ImageView) findViewById(R.id.iv_home));
        lsImageView.add((ImageView) findViewById(R.id.iv_order));
//        lsImageView.add((ImageView) findViewById(R.id.iv_fj));
        lsImageView.add((ImageView) findViewById(R.id.iv_my));

        lsTabView.add(findViewById(R.id.tab_home));
        lsTabView.add(findViewById(R.id.tab_order));
//        lsTabView.add(findViewById(R.id.tab_fj));
        lsTabView.add(findViewById(R.id.tab_my));
    }

    @Override
    protected void initData() {
        lianer_tab.setVisibility(View.GONE);
        mContext = this;
        toolbar.setTitle("首页");
        setSupportActionBar(toolbar);
        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        lsFragment.add(DpOrderFrmager.class);
        lsFragment.add(PsOrderFrmager.class);
        lsFragment.add(QscxOrderFrmager.class);
        mainAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), lsFragment);
        mViewPager.setAdapter(mainAdapter);
        setSelection(0);

        tv_name.setText(MyApplication.getUserInfo().getRealName());
        tv_accunt.setText(MyApplication.getUserInfo().getUsername());
        NowVersion = getVersion();
        tv_bbh.setText("版本号:" + NowVersion);
        mViewPager.setOffscreenPageLimit(3);//设置缓存view 的个数（实际有3个，缓存2个+正在显示的1个）
        cheakUpDate();
    }

    @Override
    protected void initEvents() {
        mViewPager.setOnPageChangeListener(new myOnPageChangeListener());
        for (View v : lsTabView) {
            v.setOnClickListener(new mOnClick());
        }
        navigationView.setNavigationItemSelectedListener(this);
    }

//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        ViewTreeObserver vto = mViewPager.getViewTreeObserver();
//        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                mViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//                viewPagerH = mViewPager.getHeight();
//                viewPagerW = mViewPager.getWidth();
//                LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) mViewPager.getLayoutParams(); //取控件textView当前的布局参数
//                linearParams.height = viewPagerH;// 控件的高强制设成20
//                linearParams.width = viewPagerW;// 控件的宽强制设成30
//                mViewPager.setLayoutParams(linearParams); //使设置好的布局参数应用到控件</pre>
//            }
//        });
//    }

    class mOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int i = 0;
            for (View v1 : lsTabView) {

                if (v1.getId() == v.getId()) {

                    mViewPager.setCurrentItem(i);
                    setSelection(i);

                }
                i++;
//                selectIndex=i;
            }
        }
    }

    class myOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            setSelection(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        int i = 0;
        if (id == R.id.nav_camera) {
            i = 0;
        } else if (id == R.id.nav_gallery) {
            i = 1;
        }
//        else if (id == R.id.nav_slideshow) {
//            i = 2;
//        }
        else if (id == R.id.nav_manage) {
            i = 2;
        } else if (id == R.id.nav_switchAccount) {
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean(Constant.IS_USER_LOGIN_KEY, false);
            edit.commit();
            Intent intent = new Intent();
            intent.setClass(mContext, LoginActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.nav_signOut) {
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean(Constant.IS_USER_LOGIN_KEY, false);
            edit.commit();
            finish();
        }
        mViewPager.setCurrentItem(i);
        setSelection(i);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void setSelection(int index) {
        for (int i = 0; i < lsImageView.size(); i++) {
            if (i == index) {
                lsImageView.get(i).setSelected(true);
            } else {
                lsImageView.get(i).setSelected(false);
            }
        }
        for (int i = 0; i < lsTextView.size(); i++) {
            if (i == index) {
                lsTextView.get(i).setSelected(true);
                lsTextView.get(i).setTextColor(mContext.getResources().getColor(R.color.tab_text_pressed));
            } else {
                lsTextView.get(i).setSelected(false);
                lsTextView.get(i).setTextColor(mContext.getResources().getColor(R.color.tab_text_normol));
            }
        }
        for (int i = 0; i < titles.length; i++) {
            if (i == index) {
                toolbar.setTitle(titles[i]);
            }
        }
    }

//    @Override
//    protected void exitApp() {
//        finish();
//    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序。", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */

    private void cheakUpDate() {
        ShowVersionTask showVersionTask = new ShowVersionTask();
        showVersionTask.execute();
    }

    public class ShowVersionTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(String... params) {
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("getAppVersion"), "");
        }

        @Override
        protected void onPostExecute(final String result) {

            if (result == null || result.length() == 0) {
                T.showShort(mContext, "连接服务器异常。");
            }
            if (result.indexOf("successMsg") > 0) {
                String successMsg = JsonUtil.getMsg(result, "successMsg");
                AppInfo appInfo = JsonUtil.getPerson(successMsg, AppInfo.class);
                NowVersion = getVersion();
                if (NowVersion.equals(appInfo.getVersion())) {
//                    T.showShort(mContext, "未发现新版本");

                } else {
//                    UpdateManager mUpdateManager = new UpdateManager(mContext);
//                    mUpdateManager.checkUpdateInfo();
                }

            } else if (result.indexOf("errorMsg") > 0) {
                String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                T.showShort(mContext, errorMsg);
            }
        }

    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}